package com.wen.qqrobot.util;

import com.wen.qqrobot.Config;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by wenwen on 2016/10/5.
 * version 1.0
 */
public class Shell {

    public static String exec(String cmd) {
        System.out.println("cmd: " + cmd);
        ProcessBuilder pb = new ProcessBuilder(getCmd(cmd));
        pb.directory(new File(Config.getInstance().getDirectory()));
        pb.redirectErrorStream(true);
        StringBuilder buffer = new StringBuilder(100);
        try {
            Process pro = pb.start();
            readFromInput(pro.getInputStream(), buffer);
            int exitVal = pro.waitFor();
            buffer.append("\n").append("Process exitValue: ").append(exitVal);
        } catch (Exception ex) {
            ex.printStackTrace();
            return "(。_。) 对不起，运行命令出错了~";
        }
        return buffer.toString();
    }

    private static void readFromInput(InputStream is, StringBuilder buffer)
            throws IOException {
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line).append("\n");
            }
        } finally {
            if (isr != null) {
                isr.close();
                isr = null;
            }
            if (br != null) {
                br.close();
                br = null;
            }
        }
    }

    private static String[] getCmd(String cmd) {
        cmd = cmd.trim().replace("\n", "&&");
        String osName = System.getProperty("os.name", "");
        if (osName.startsWith("Windows")) {
            return new String[]{"cmd", "/C", cmd};
        }
        return new String[]{"/bin/sh", "-c", cmd};
    }

    public static void main(String[] args) {
        System.out.println(exec("dir"));
    }
}
